package com.zrrd.jt_admin.manager.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.jt_admin.common.bo.RuleBo;
import com.zrrd.jt_admin.common.entity.Rule;
import com.zrrd.jt_admin.common.page.RulePageVo;
import com.zrrd.jt_admin.common.vo.RuleVo;
import com.zrrd.jt_admin.manager.mapper.RuleMapper;
import com.zrrd.jt_admin.manager.service.RuleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wanjl
 * @since 2024-06-25
 */
@Service
public class RuleServiceImpl extends ServiceImpl<RuleMapper, Rule> implements RuleService {
    @Resource
    private RuleMapper ruleMapper;
    /**
     * 根据角色id，查询该角色的权限列表
     *
     * @param roleId
     * @return
     */
    @Override
    public List<RuleBo> getRuleListByRoleId(Integer roleId) {
        List<Rule> list = ruleMapper.getRuleListByRoleId(roleId);
        List<RuleBo> ruleBos = list.stream().map(rule -> {
            RuleBo ruleBo = new RuleBo();
            BeanUtils.copyProperties(rule, ruleBo);
            return ruleBo;
        }).collect(Collectors.toList());
        List<RuleBo> ruleBoList = iteratorRuleList(ruleBos, 0);
        return ruleBoList;
    }


    private List<RuleBo> iteratorRuleList(List<RuleBo> ruleBoList,Integer pId) {
        List<RuleBo> rbList = new ArrayList<>();
        ruleBoList.forEach(ruleBo -> {
            Integer id = ruleBo.getId();//权限菜单记录的id
            Integer parentId = ruleBo.getRuleId();//权限菜单记录的父id
            if (parentId == pId) {
                List<RuleBo> list = iteratorRuleList(ruleBoList, id);
                ruleBo.setChild(list);
                rbList.add(ruleBo);
            }
        });
        return rbList;
    }


    /**
     * 分页查询
     *
     * @param page
     * @return
     */
    @Override
    public RulePageVo findByPage(int page) {
        RulePageVo rulePageVo = new RulePageVo();

        List<RuleBo> ruleBos = list().stream().map(rule -> {
            RuleBo ruleBo = new RuleBo();
            BeanUtils.copyProperties(rule, ruleBo);
            return ruleBo;
        }).collect(Collectors.toList());

        List<RuleBo> ruleBoList = iteratorRuleList(ruleBos, 0);

        rulePageVo.setList(ruleBoList);
        //查询所有权限列表信息
        List<RuleVo> ruleVoList = list().stream().map(rule -> {
            RuleVo ruleVo = new RuleVo();
            BeanUtils.copyProperties(rule, ruleVo);
            ruleVo.setLevel();
            return ruleVo;
        }).collect(Collectors.toList());

        rulePageVo.setRules(ruleVoList);

        rulePageVo.setTotalCount(Long.valueOf(ruleVoList.size()));

        return rulePageVo;
    }



}
